import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
import Cookie from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isCollapse: false,
    tabslist:[
      {
        path: '/',
        name: 'home',
        label: '首页',
        icon: 'home'
      }
    ],
    currentMenu:null,
    menu:[]
  },
  mutations: {
    collapseMenu(state){
      state.isCollapse = !state.isCollapse
    },
    selectMenu(state,val){
      if(val.name !== 'home'){
        state.currentMenu = val
        const resut = state.tabslist.findIndex(item => item.name === val.name)
        if(resut === -1) {
          state.tabslist.push(val)
        }
      }else{
        state.currentMenu = null
      }
    },
    closeTag(state,val){
      const result = state.tabslist.findIndex(item => item.name === val.name)
      state.tabslist.splice(result, 1)
    },
    setmenu(state,val){
      state.menu = val
      Cookie.set('menu',JSON.stringify(val))
    },
    clearMenu(state){
      state.menu = []
      Cookie.remove("menu")
    },
    addMenu(state,router){
      if(!Cookie.get('menu')){
        return
      }
      const menu = JSON.parse(Cookie.get('menu'))
      state.menu = menu
      
      const menuArray = []
      menu.forEach(item =>{
        if(item.children){
          // 如果存在二级菜单就继续遍历
          item.children = item.children.map(item =>{
            item.component = () => import(`../views/${item.url}`)
            return item
          })
          menuArray.push(...item.children)
        }else{
          item.component = () => import(`../views/${item.url}`)
          menuArray.push(item)
        }
      });
      // 动态路由的添加
      menuArray.forEach(item =>{
        router.addRoute('Main',item)
      })
    }
  },
  actions: {
  },
  modules: {
    user,
  }
})
